#include "file.h"

File::File() {}

void File::write(const QString &filepath, const QStringList &header, const QStringList &data, bool writeHeader)
{
    QFile file(filepath);
    // 以写入模式打开文件，如果文件不存在则创建它，文本模式
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qDebug() << "Error opening file for writing:" << file.errorString();
        return;
    }
    QTextStream out(&file);
    if (writeHeader) {
        out << header.join(",") << "\n";
    }
    for (const QString &line : data) {
        out << line << "\n";
    }
    file.close();
}

bool File::read(const QString &filepath, QStringList &header, QStringList &data)
{
    QFile file(filepath);
    // 以读取模式打开文件，文本模式
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Error opening file for reading:" << file.errorString();
        return false;
    }
    QTextStream in(&file);
    QString line;
    // 读取第一行作为表头
    if (in.atEnd() == false) {
        header = in.readLine().split(",");
    }
    // 读取剩余的行作为数据
    while (in.atEnd() == false) {
        line = in.readLine();
        data.append(line.split(","));
    }
    file.close();
    return true;
}
